import _ from 'lodash';
import { useMenuStore } from '@/store';
import router from '@/router';

// 获取当前匹配到的路由
const getRoute = (path) => {
  const { matched } = router.resolve(path);
  const strictMatched = matched.at(-1);
  return strictMatched;
};

// 菜单需要合并部分路由属性： 比如图标啥的
export const handleMenus = (oldMenus = useMenuStore().menus) => {
  const newMenus = _.cloneDeep(oldMenus);
  const handler = (menus) => {
    menus.forEach((item) => {
      const route = getRoute(item.path);
      if (route.path === item.path) {
        for (const key in route.meta) {
          item[key] = route.meta[key];
        }
      }
      if (item.children) handler(item.children);
    });
  };
  handler(newMenus);
  return newMenus;
};

// 根据路由获取菜单配置
const getMenu = (path) => {
  const menusTabs = useMenuStore();
  let menu;
  const handler = (menus) => {
    for (const item of menus) {
      if (item.path === path) {
        menu = item;
        break;
      } else {
        if (item.children) handler(item.children);
      }
    }
  };
  handler(menusTabs.menus);
  return menu;
};

/**
 * 根据路由 来更新顶部Tab
 */
export const updateTabByRouter = (toPath: string) => {
  const route = getRoute(toPath);
  const isErrPage = route.meta.type === 'err';
  if (isErrPage) return false; // 如果错误页面，就不要在开标签了
  const store = useMenuStore();
  // 查找当前路由匹配到对应的菜单
  const currentMenu = getMenu(toPath);
  // 然后根据菜单判断该菜单是否已经被打开过，如果是则激活，否则新增
  const exit = store.tabs.find((it) => it.path === toPath);
  if (currentMenu) {
    if (!exit) store.addTab(currentMenu);
    store.setactiveTab(currentMenu.path);
  }
};
